import { Msger } from "../Msger";
import { GameLocalStorage } from "../ComClass";

// Learn TypeScript:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator;

@ccclass
export default class LevelProgressSc extends cc.Component {


    @property(cc.Label)
    beginNumber: cc.Label = null;
    @property(cc.Label)
    endNumber: cc.Label = null;
    // LIFE-CYCLE CALLBACKS:
    private levelProgressBar: cc.ProgressBar = null;
    onLoad() {
        this.levelProgressBar = this.getComponent(cc.ProgressBar);        
        Msger.on(Msger.on_level_progress_zero, this.on_level_progress_zero, this);
        Msger.on(Msger.on_add_score, this.on_add_score, this);
        Msger.on(Msger.on_level_progress_update, this.nextLevelScoreCreate, this);
    }

    start() {
    }

    // update (dt) {}
    private score = 0;
    private nextLevelScore = 0;
    private nextLevelScoreCreate(score){   
        if(score && score != 0){
            this.score = GameLocalStorage.gameData.levelprogressscore;
        }
        let level = GameLocalStorage.gameData.level;        
        let levelprogress = GameLocalStorage.gameData.levelprogress;
        this.nextLevelScore = 800 + 60 * level + levelprogress * 1000;
        this.beginNumber.string = level.toString();
        this.endNumber.string = (level + 1).toString();
        this.on_add_score(0);
    }
    private on_level_progress_zero() {
        GameLocalStorage.gameData.level = 1;
        this.score = 0;
        this.levelProgressBar.progress = 0;
        GameLocalStorage.gameData.levelprogress = 0;
        this.nextLevelScoreCreate(0);
    }
    private on_add_score(score){
        this.score += score;
        if(this.score >= this.nextLevelScore){
            //超过了标准分数
            this.score = 0;
            GameLocalStorage.gameData.level += 1;
            GameLocalStorage.gameData.levelprogress += 1;            
            this.levelProgressBar.progress = 0;
            this.nextLevelScoreCreate(0);
            Msger.emit(Msger.on_level_up);
        }else{
            this.levelProgressBar.progress = (this.score) / this.nextLevelScore;
        }
        GameLocalStorage.gameData.levelprogressscore = this.score;
    }
}
